package com.fc.redap.service.impl;

import com.fc.redap.dao.BaseDao;
import com.fc.redap.dao.SmsHistoryDao;
import com.fc.redap.entity.SMSModule;
import com.fc.redap.entity.SmsHistoryEntity;
import com.fc.redap.exception.ResponseException;
import com.fc.redap.helper.DateTimeHelper;
import com.fc.redap.helper.RandomUtils;
import com.fc.redap.helper.StringUtils;
import com.fc.redap.props.SmsProps;
import com.fc.redap.service.ISmsHistoryService;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;

@Service
public class SmsHistoryServiceImpl extends BaseServiceImpl<SmsHistoryEntity> implements ISmsHistoryService {

    private final static int DELAY = 300;//5 mints

    @Autowired
    SmsHistoryDao smsDao;

    @Autowired
    private SmsProps smsProps;

    public BaseDao getDao(){
        return smsDao;
    }

    public SmsHistoryEntity queryObject(Long id){
        return smsDao.queryObject(id);
    }

    public List<SmsHistoryEntity> queryList(Map<String, Object> map){
        return smsDao.queryList(map);
    }

    public int queryTotal(Map<String, Object> map){
        return smsDao.queryTotal();
    }

    public void send(String phone, SMSModule module) {

        //Generator code.
        final boolean isPhone = StringUtils.isPhoneString(phone);
        if (!isPhone) {
            throw new ResponseException("无效的手机号", HttpServletResponse.SC_BAD_REQUEST);
        }
        if (module == SMSModule.other) {
            throw new ResponseException("无效的模块名", HttpServletResponse.SC_BAD_REQUEST);
        }

        SmsHistoryEntity smsEntity = smsDao.queryLastSms(phone, module.getDbValue());
        if (smsEntity != null) {
            int currentSecond = DateTimeHelper.getEpochTimeInSecond(new Date());
            if (smsEntity.getExpireTime() > currentSecond) {
                throw new ResponseException("请等待1分钟再次发送", HttpServletResponse.SC_CONFLICT);
            }
        }

        final String randomCode = RandomUtils.generateRandomNumber(6);

        //TODO: Send to SMS GATEWAY
        String smsContent =  "您好，您的验证码是"+randomCode;
        sendToSmsGateway(smsContent, phone);

        int createTime = DateTimeHelper.getEpochTimeInSecond(new Date());
        SmsHistoryEntity newSmsHistory = new SmsHistoryEntity();
        newSmsHistory.setCode(randomCode);
        newSmsHistory.setCreateTime(createTime);
        newSmsHistory.setExpireTime(createTime + DELAY);
        newSmsHistory.setModule(module.getDbValue());
        newSmsHistory.setPhone(phone);
        newSmsHistory.setStatus(0);
        smsDao.save(newSmsHistory);
    }

    public void save(SmsHistoryEntity sms){
        smsDao.save(sms);
    }

    public void update(SmsHistoryEntity sms){
        smsDao.update(sms);
    }

    public void delete(Long id){
        smsDao.delete(id);
    }

    public void deleteBatch(Long[] ids){
        smsDao.deleteBatch(ids);
    }

    @Override
    public void send(String phone, String msg) {
        final boolean isPhone = StringUtils.isPhoneString(phone);
        if (!isPhone) {
            throw new ResponseException("无效的手机号", HttpServletResponse.SC_BAD_REQUEST);
        }
        sendToSmsGateway(msg, phone);
    }

    public SmsHistoryEntity queryByMobileAndCode(String phone, String  code){
        return smsDao.queryByMobileAndCode(phone, code);
    }

    /**
     * 创蓝短信接口
     * @param message
     * @param mobiles
     */
    private void sendToSmsGateway(String message, String mobiles) {
        if(mobiles == null || "".equals(mobiles)){
            return;
        }
        if(message == null || "".equals(message)){
            return;
        }
        String url = "http://222.73.117.156/msg/HttpBatchSendSM?";
        StringBuffer queryString = new StringBuffer();
        queryString.append("account=");
        queryString.append(smsProps.getAccount());
        queryString.append("&pswd=");
        queryString.append(smsProps.getPassword());
        queryString.append("&needstatus=true");
        queryString.append("&mobile=");
        queryString.append(mobiles);
        queryString.append("&msg=");
        queryString.append(message);
        queryString.append("&currentTime=");
        queryString.append(System.currentTimeMillis());
        url = url + queryString.toString();
        HttpGet httpGet = new HttpGet(url);
        try{
            HttpClient httpClient = HttpClients.createDefault();
            HttpResponse response = httpClient.execute(httpGet);
            System.out.println(response);
        }catch (IOException ioe){
            ioe.printStackTrace();
        }finally {
            httpGet.releaseConnection();
        }
    }
}
